package util;

import java.net.URL;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException; 

import exceptions.CepNotFoundException;

import basicas.Endereco;

public class CepConsulta {

	public static Endereco consultaCep(String cep) {
		
		Endereco endereco = new Endereco();

		String url = "http://cep.republicavirtual.com.br/web_cep.php?cep="+cep+"&formato=xml";

		try {

			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
			Document doc = docBuilder.parse (new URL(url).openStream());

			// normalize text representation
			//doc.getDocumentElement ().normalize ();

			NodeList listOfCeps = doc.getElementsByTagName("webservicecep");

			Node node = listOfCeps.item(0);

			if(node.getNodeType() == Node.ELEMENT_NODE){

				Element nodeElement = (Element)node;

				NodeList resultadoList = nodeElement.getElementsByTagName("resultado");
				Element resultadoElement = (Element)resultadoList.item(0);
				NodeList childResultadoList = resultadoElement.getChildNodes();


				if(((Node)childResultadoList.item(0)).getNodeValue().trim().equals("0")){
					throw new CepNotFoundException("CEP nao encontrado");
				} else {

					//-------
					NodeList ufList = nodeElement.getElementsByTagName("uf");
					Element ufElement = (Element)ufList.item(0);
					NodeList childUFList = ufElement.getChildNodes();
					endereco.setUf(((Node)childUFList.item(0)).getNodeValue().trim());

					//-------					
					NodeList cidadeList = nodeElement.getElementsByTagName("cidade");
					Element cidadeElement = (Element)cidadeList.item(0);
					NodeList childCidadeList = cidadeElement.getChildNodes();
					endereco.setCidade(((Node)childCidadeList.item(0)).getNodeValue().trim());

					//-------
					NodeList bairroList = nodeElement.getElementsByTagName("bairro");
					Element bairroElement = (Element)bairroList.item(0);
					NodeList childBairroList = bairroElement.getChildNodes();
					endereco.setBairro(((Node)childBairroList.item(0)).getNodeValue().trim());

					//-------
					NodeList tipoLogradouroList = nodeElement.getElementsByTagName("tipo_logradouro");
					Element tipoLogradouroElement = (Element)tipoLogradouroList.item(0);
					NodeList childTipoLogradouroList = tipoLogradouroElement.getChildNodes();
					endereco.setTipoLogradouro(((Node)childTipoLogradouroList.item(0)).getNodeValue().trim());

					//-------
					NodeList logradouroList = nodeElement.getElementsByTagName("logradouro");
					Element logradouroElement = (Element)logradouroList.item(0);
					NodeList childLogradouroList = logradouroElement.getChildNodes();
					endereco.setLogradouro(((Node)childLogradouroList.item(0)).getNodeValue().trim());

					//-------
				}//end of else clause


			}//end of if clause


		}catch (SAXParseException err) {
			System.out.println ("** Parsing error" + ", line " 
					+ err.getLineNumber () + ", uri " + err.getSystemId ());
			System.out.println(" " + err.getMessage ());

		}catch (SAXException e) {
			Exception x = e.getException ();
			((x == null) ? e : x).printStackTrace ();

		}catch (Exception e) {
			e.printStackTrace ();
		}
		//System.exit (0);
		return endereco;

	}//end of main

}